<template>
  <div class="login-container">
    <el-form
      v-show="restPwdFlag"
      ref="provingForm"
      :model="provingForm"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h1 class="title">重置密码</h1>
      </div>

      <el-form-item>
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="provingForm.username"
          placeholder="Username"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>
      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <div class="verificationCode">
          <el-form-item>
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="code"
              v-model="provingForm.code"
              placeholder="verification code"
              :type="passwordType"
              name="code"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="attestationVerificationCode"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-button
            v-show="sendBotShouFlag"
            :disabled="disabled"
            type="primary"
            style="width:24%;margin:7px 0 30px 10px;"
            @click.native.prevent="handleVerificationCode"
          >发送验证码</el-button>
          <el-button
            v-show="!sendBotShouFlag"
            :disabled="true"
            type="primary"
            style="width:24%;margin:7px 0 30px 10px;"
          >{{times}} S</el-button>
        </div>
      </el-tooltip>
      <div class="setBtn">
        <el-button
          type="primary"
          style="width:35%;margin-bottom:30px;"
          @click.native.prevent="back"
        >取消</el-button>
        <el-button
          :loading="loading"
          :disabled="nextDisabled"
          type="primary"
          style="width:100%;margin-bottom:30px;"
          @click.native.prevent="attestationVerificationCode"
        >下一步</el-button>
      </div>
    </el-form>

    <el-form
      v-show="!restPwdFlag"
      ref="resetPwdForm"
      :model="resetPwdForm"
      :rules="resetPwdRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h1 class="title">设置新密码</h1>
      </div>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordTypeC"
          ref="password"
          v-model="resetPwdForm.password"
          :type="passwordTypeC"
          placeholder="Password"
          name="password"
          tabindex="1"
          autocomplete="on"
        />
        <span class="show-pwd" @click="showPswd">
          <svg-icon :icon-class="passwordTypeC === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="resetPwdForm.confirmPassword"
            :type="passwordType"
            placeholder="Confirm Password"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>
      <div class="setBtn">
        <el-button
          type="primary"
          style="width:35%;margin-bottom:30px;"
          @click.native.prevent="back"
        >取消</el-button>
        <el-button
          :loading="sureLoading"
          type="primary"
          style="width:100%;margin-bottom:30px;"
          @click.native.prevent="handleLogin"
        >确定</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { Message } from "element-ui";
export default {
  name: "ResetPassword",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/;
      const result = re.test(value);
      if (!value) {
        callback("密码不能为空");
      } else {
        if (!result) {
          callback(new Error("密码必须包含大小写字母和数字，长度为8~16位"));
        } else {
          callback();
        }
      }
    };
    return {
      provingForm: {
        username: "",
        code: ""
      },
      resetPwdForm: {
        username: "",
        password: "",
        confirmPassword: ""
      },
      resetPwdRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      disabled: true,
      nextDisabled: true,
      sendBotShouFlag: true,
      restPwdFlag: true,
      times: 60,
      timer: null,
      passwordType: "password",
      passwordTypeC: "password",
      capsTooltip: false,
      loading: false,
      sureLoading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    },
    provingForm: {
      handler(newObj, oldObj) {
        if (newObj.username != "") {
          this.disabled = false;
        } else {
          this.disabled = true;
        }
        if (newObj.username != "" && newObj.code != "") {
          this.nextDisabled = false;
        } else {
          this.nextDisabled = true;
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    // if (this.provingForm.username === "") {
    //   this.$refs.username.focus();
    // }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    showPswd() {
      if (this.passwordTypeC === "password") {
        this.passwordTypeC = "";
      } else {
        this.passwordTypeC = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.resetPwdForm.validate(valid => {
        if (valid) {
          if (
            this.resetPwdForm.password === this.resetPwdForm.confirmPassword
          ) {
            this.sureLoading = true;
            this.$axios
              .post("mgr/upDatePassword", this.resetPwdForm)
              .then(() => {
                Message.success("密码已修改");
                this.$router.push({
                  path: this.redirect || "/",
                  query: this.otherQuery
                });
                this.sureLoading = false;
              })
              .catch(() => {
                this.sureLoading = false;
              });
          } else {
            Message.warning("两次密码不相同，请确认");
            // this.$set(this.resetPwdForm, "password", "");
            // this.$set(this.resetPwdForm, "confirmPassword", "");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleVerificationCode() {
      this.times = 60;
      this.sendBotShouFlag = false;
      setTimeout(() => {
        this.sendBotShouFlag = true;
      }, 60000);
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        this.times += -1;
        if (this.times == 0) {
          clearInterval(this.timer);
        }
      }, 1000);
      this.$axios.post("mgr/sendCode", this.provingForm).then(res => {
        if (res.data.code == 1) {
          Message.error("用户名不存在，请确认用户名已存在");
          this.sendBotShouFlag = true;
          clearInterval(this.timer);
          this.times = 60;
        }
        if (res.data.code == 0) {
          Message.success("验证码已发送至邮箱，请注意查看");
        }
      });
    },
    attestationVerificationCode() {
      this.loading = true;
      this.$axios
        .post("mgr/reviewCode", this.provingForm)
        .then(res => {
          if (res.data.code == 1) {
            Message.error("验证码校验失败，请确认校验信息正确");
            this.loading = false;
          }
          if (res.data.code == 0) {
            this.$set(this.resetPwdForm, "username", this.provingForm.username);
            this.loading = false;
            this.restPwdFlag = false;
          }
        })
        .catch(() => {
          this.loading = false;
          this.restPwdFlag = true;
        });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    resetPassword() {
      this.$router.push({ path: "reset-password" });
    },
    back() {
      this.$router.back();
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .verificationCode {
    display: flex;
    .el-form-item {
      flex: 1;
      .el-input {
        width: 83%;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  overflow: hidden;
  min-width: 1280px;
  background: url(../../assets/img/main_logo.png) 0px center no-repeat,linear-gradient(-45deg, #133354, rgba(61, 94, 115, 0.55));
  background-size: cover;
  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    overflow: hidden;
    display: block;
    position: fixed;
    _position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -200px;
    margin-top: -200px;
    z-index: 10001;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
.setBtn {
  display: flex;
  justify-content: space-between;
}
</style>
